package com.iamteer.day18.autoincrement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class EmpDao {
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";
	
	//保存员工，同时保存关联的部门
	public void save(Employee employee) {
		//保存部门
		String sql_dept = "INSERT INTO dept(deptName) VALUES(?)";
		//保存员工
		String sql_emp = "INSERT INTO employee(empName,dept_id) VALUES(?,?)";
		//部门 ID
		int deptId = 0;
		
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			//2 保存部门，获取自增长值
			//2.1 指定返回自增长标记
			pstmt = con.prepareStatement(sql_dept, Statement.RETURN_GENERATED_KEYS);
			//2.2 设置参数
			pstmt.setString(1, employee.getDept().getDeptName());
			//2.3 执行
			pstmt.executeUpdate();
			//2.4 获取自增长值
			rs = pstmt.getGeneratedKeys();
			if (rs.next()) {
				deptId = rs.getInt(1);
			}
			
			//3 保存员工
			pstmt = con.prepareStatement(sql_emp);
			//3.1 设置参数
			pstmt.setString(1, employee.getEmpName());
			pstmt.setInt(2, deptId);
			//3.2 执行
			pstmt.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
